<template>
  <div>
    <div class="top-title">
      <span class="tinyTitle">
        <div class="titleFlag"></div>
        {{ "薪资范围对比" }}
      </span>
    </div>
    <template v-if="activeName == 'full'">
      <div class="regionSalaryBasic">
        <el-row class="search-container">
          <el-form ref="form" :model="form" label-width="auto">
            <el-form-item label="统计时间">
              <el-date-picker
                v-model="selectBetweenTime"
                size="small"
                type="monthrange"
                :clearable="false"
                align="right"
                unlink-panels
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                :picker-options="pickerOptions"
                @change="handleDateChange"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="区域名称">
              <regoinSearch ref="regionRef" @onRegionChange="onRegionChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="fetchData()"
                >查询</el-button
              >
              <el-popover
                placement="top-start"
                width="200"
                trigger="hover"
                content="通过您的筛选条件，计算平均薪酬以及职位总数"
              >
                <el-button
                  slot="reference"
                  type="primary"
                  plain
                  @click="fetchTotalData()"
                  style="margin-left: 10px"
                  >计算查询结果
                </el-button>
              </el-popover>
              <el-button
                v-if="!isDisabledEdit"
                type="primary"
                @click="handleSaveClick()"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-row>
        <div class="list">
          <el-tooltip effect="light" placement="top">
            <div class="toolTipGuide" slot="content">
              <div class="toolTipTitle"></div>
              <div
                class="toolTipItems"
                v-for="(item, index) in stepInfo"
                :key="index"
              >
                <div class="stepImageContainer">
                  <img :src="item.stepImage" class="stepImage" />
                </div>
                <div class="stepDesc">{{ item.stepDesc }}</div>
              </div>
            </div>
            <el-button
              size="mini"
              class="filter-item"
              icon="el-icon-download"
              @click="onExportClick"
              >导出
            </el-button>
          </el-tooltip>
          <el-table
            :class="{ inputEdit: true, isDisabledEdit: !isDisabledEdit }"
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            @sort-change="sortChange"
          >
            <el-table-column label="区域名称">
              <template slot-scope="scope">
                {{ scope.row.salaryRegionName }}
              </template>
            </el-table-column>
            <el-table-column
              label="平均薪酬"
              prop="salary_num"
              sortable="custom"
              header-cell-style="background-color: lightblue;"
              cell-style="background-color: lightyellow;"
            >
              <template
                slot-scope="scope"
                header-cell-style="background-color: lightblue;"
              >
                <el-input
                  :class="{ inputEdit: true, isDisabledEdit: !isDisabledEdit }"
                  v-model="scope.row.salaryNum"
                  :disabled="isDisabledEdit"
                  @input="handleRowClick(scope.row)"
                  placeholder="请输入薪资"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="职位数量"
              prop="company_num"
              sortable="custom"
            >
              <template slot-scope="scope">
                {{ scope.row.companyNum }}
              </template>
            </el-table-column>
            <el-table-column
              label="统计时间"
              prop="salary_num"
              sortable="custom"
            >
              <template slot-scope="scope">
                {{ scope.row.generateTime.slice(0, 7) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="tablePage.pageNum"
            :page-size="tablePage.pageSize"
            :page-sizes="pageSizes"
            :total="tablePage.total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </template>
    <div class="regionSalaryContent">
      <div class="echart" v-if="activeName == 'chart'">
        <div class="regionLineChart">
          <salaryComparisonChart :regionLineDescAvg.sync="regionLineDescAvg" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getRegionSalaryList,
  getRegionSalaryTotalData,
  getRegionSalaryListExport,
  updateRegion,
} from "@/api/salary";
import SelectRegion from "@/components/SelectRegion";
import regoinSearch from "@/views/position/components/regoinSearch";
import regionLineChart from "@/views/position/components/regionLineChart";
import regionBarChart from "@/views/position/components/regionBarChart";
import browser from "browser-tool";
import salaryComparisonChart from "@/views/position/components/salaryComparisonChart";

export default {
  name: "salaryComparison",
  components: {
    SelectRegion,
    regoinSearch,
    regionLineChart,
    regionBarChart,
    salaryComparisonChart,
  },
  data() {
    return {
      isShitBrowser: false,
      hoverName: "",
      hoverValue: "",
      regionLineDescAvg: "",
      regionBarDescAvg: "",
      activeName: "chart",
      chartData: {},
      myChart: null,
      list: null,
      totalData: {
        salaryNum: null,
        companyNum: null,
      },
      listLoading: true,
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 0, // 总记录数
      },
      positionName: "",
      selectTime: "",
      regionId: "",
      regionList: [],
      currentRegionName: "",
      pageSizes: [10, 20, 30],
      orderByColumn: "",
      orderBy: "",
      form: {},
      selectBetweenTime: [],
      // 时间选择器
      pickerOptions: {
        shortcuts: [
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      stepInfo: [
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide1.png",
          stepDesc: "第一步，打开导出文件",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide2.png",
          stepDesc: "第二步，选择数据范围。",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide3.png",
          stepDesc: "第三步，选择全部图表",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide4.png",
          stepDesc: "第四步，选择自己需要的样式备份",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide5.png",
          stepDesc: "第五步，图表制作完成啦！",
        },
      ],
      isDisabledEdit: true,
      editStatus: "编辑",
      editDataList: [],
    };
  },
  created() {
    // this.fetchData();

    this.positionName = this.$route.query.name;
    const browserInfo = browser();
    if (browserInfo.browser != "Chrome") {
      this.isShitBrowser = true;
    }
  },
  mounted() {},
  methods: {
    handleClick() {
      if (this.activeName == "full") {
        this.regionList = [];
        let date = new Date();
        let currentMonth = date.getMonth() + 1;
        let value =
          date.getFullYear() +
          "-" +
          (currentMonth < 10 ? "0" : "") +
          currentMonth +
          "-" +
          "01";

        // 默认显示上月日期
        let date1 = new Date();
        date1.setMonth(date1.getMonth() - 1); // 减去一个月
        let previousMonth = date1.getMonth() + 1;
        let value1 =
          date1.getFullYear() +
          "-" +
          (previousMonth < 10 ? "0" : "") +
          previousMonth +
          "-" +
          "01";

        // 确保selectBetweenTime中的日期按照从小到大的顺序排列
        this.selectBetweenTime = [value, value1].sort();
        this.fetchData();
      }
    },
    handleDateChange(val) {
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    onRegionChange(val) {
      this.currentRegionName = val.label;
      this.regionList = [val.value];
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    initEditStutas() {
      //每次请求接口，初始化编辑状态
      this.isDisabledEdit = true;
      this.editStatus = "编辑";
      this.editDataList = [];
    },
    fetchData() {
      this.initEditStutas();

      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: this.tablePage.pageNum,
        perPage: this.tablePage.pageSize,
      };

      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "salary_num";
        params.orderBy = "desc";
      }

      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      getRegionSalaryList(params).then((response) => {
        const count = response.data.count - 0;
        this.tablePage.total = count;
        this.list = response.data.rows;
        this.listLoading = false;
      });
    },
    fetchTotalData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      this.fetchData();
      getRegionSalaryTotalData(params).then((response) => {
        if (
          response.data != null &&
          response.data.companyNum != null &&
          response.data.salaryNum != null
        ) {
          this.totalData.salaryNum = parseFloat(
            response.data.salaryNum
          ).toFixed(2);
          this.totalData.companyNum = response.data.companyNum;
        } else {
          this.totalData.salaryNum = 0;
          this.totalData.companyNum = 0;
        }
        let content =
          `<div style='border-top:1px solid #e8e8e8;border-bottom:1px solid #e8e8e8;margin-top:-10px;font-size:14px;padding:28px 0;text-align:left;'>` +
          "<div style='font-size:16px;font-weight:bold;color:#222;margin-bottom:0px;'>通过您的查询条件（岗位，地区，时间）可得：</div>" +
          "<br/>" +
          "您查询的地区：[ " +
          (this.currentRegionName == "" || this.currentRegionName == null
            ? "全国"
            : this.currentRegionName) +
          " ] " +
          "<br>" +
          " 您查询的时间区间为：[ " +
          (this.selectBetweenTime == "" || this.selectBetweenTime == null
            ? "不限时间"
            : this.selectBetweenTime) +
          " ] " +
          "<br>" +
          "  平均薪酬为： " +
          this.totalData.salaryNum +
          "<br>" +
          " 职位总数为： " +
          this.totalData.companyNum;
        +`</div>`;

        this.$alert(content, "计算查询结果", {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true,
        });
        this.listLoading = false;
      });
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      this.fetchData();
      // 在此刷新数据
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      this.fetchData();
      // 在此刷新数据
    },
    onExportClick() {
      // 导出方法
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: 1,
        perPage: 10000,
      };
      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "salary_num";
        params.orderBy = "desc";
      }

      getRegionSalaryListExport(params)
        .then((result) => {
          const link = document.createElement("a"); // 创建a标签
          const blob = new Blob([result], { type: "application/vnd.ms-excel" }); // 设置文件流
          link.style.display = "none";
          // 设置连接
          link.href = URL.createObjectURL(blob); // 将文件流转化为blob地址
          link.download =
            (this.$route.query.name != undefined
              ? this.$route.query.name
              : "") + "地区薪酬数据统计表";
          document.body.appendChild(link);
          // 模拟点击事件
          link.click(); // 设置点击事件
          this.listLoading = false;
          window.URL.revokeObjectURL(link.href); // 释放掉blob对象
          document.body.removeChild(link); // 下载完成移除元素
        })
        .catch((err) => {
          console.log(err);
        });
    },
    sortChange(column) {
      this.orderByColumn = column.prop != null ? column.prop : "salary_num";
      this.orderBy = column.order != null ? column.order : "desc";
      this.fetchData();
      // 在此刷新数据
    },
    handleRowClick(row) {
      // 使用正则表达式过滤非数字和小数点字符
      row.salaryNum = row.salaryNum.replace(/[^0-9.]/g, "");

      // 获取小数点的索引位置
      const dotIndex = row.salaryNum.indexOf(".");

      // 如果小数点存在且小数点后有多于一位的数字，则截取小数点后一位
      if (dotIndex !== -1 && row.salaryNum.length - dotIndex > 3) {
        row.salaryNum = row.salaryNum.slice(0, dotIndex + 3);
      }
      // console.log(
      //   "handleRowClick--------->",
      //   row,
      //   row.salaryNum,
      //   this.editDataList.indexOf(row)
      // );
      if (this.editDataList.indexOf(row) <= -1) {
        //是否已经存在
        this.editDataList.push(row);
      }
      // //console.log("editDataList--------->", this.editDataList);
    },
    handleEditClick() {
      if (this.isDisabledEdit) {
        this.isDisabledEdit = false;
        this.editStatus = "退出编辑";
      } else {
        if (this.editDataList.length > 0) {
          this.$confirm("此操作将不保存已修改内容, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              //不保存数据，重新请求，刷新数据
              this.fetchData();
            })
            .catch(() => {
              //保持不变
            });
        } else {
          //不保存数据，重新请求，刷新数据
          this.fetchData();
        }
      }
    },
    handleSaveClick() {
      this.$confirm("此操作将覆盖原有内容, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //保存数据成功，重新请求，刷新数据
          this.saveEditData();
        })
        .catch(() => {
          //保持不变
        });
    },
    saveEditData() {
      // 保存编辑的数据
      this.listLoading = true;
      this.editDataList.forEach((item, index) => {
        item.generateTime = item.generateTime + "-01"; //后台要求拼接年月日
      });
      const params = this.editDataList;
      //console.log("saveEditData-------->", params);
      updateRegion(params)
        .then((result) => {
          this.listLoading = false;
          //console.log("updateRegion-------->", params);
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "保存成功",
            });
            this.initEditStutas();
            // // 添加个异步操作，不然获取到的值总是上一次变化的值
            // setTimeout(() => {
            //   this.fetchData();
            // }, 1000);
          } else {
            this.$message({
              type: "warning",
              message: result.status_desc,
            });
          }
        })
        .catch((err) => {
          this.listLoading = false;
          console.log(err);
        });
    },
  },
};
</script>

<style scoped lang="scss">
.list {
  /* height: 630px;
    overflow-y: auto; */
}
.app-container {
  padding-top: 0px;
  padding-right: 0px;
  // min-height: calc(100vh - 190px);
  overflow: hidden;
  // width: 100%;
  /* max-height: calc(100vh - 100px); */
  /* background: linear-gradient(180deg, #eaf5ff 0%, #ffffff 100%); */
  background-image: url("https://upload.yl1001.com/upload/images/view?file=Q,tr--ap_8c=fney6Bg2IJzH69mz6q=xfFRO5e57Imp9e0psmHce_CdVSB9mv.png");
  background-size: 100% 139px;
  background-repeat: no-repeat;
  border-radius: 10px 8px 8px 8px;
  border: 0;
  background-attachment: fixed;
  background-position: 200px 139px;
  padding-top: 10px;
}
.top-title {
  display: flex;
  margin: 20px 40px 10px 0px;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #222;
  font-weight: bold;
  margin-right: 40px;

  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
}
.top-line {
  height: 1px;
  background-color: #cfd8f5;
  margin: -24px 0px 20px 140px;
}
.regionSalaryContent,
.regionSalaryBasic {
  position: relative;
  display: flow-root;
  margin-top: 20px;
  // max-height: calc(100vh - 192px);
  // overflow-y: scroll;

  // padding-right: 56px;
  &::-webkit-scrollbar {
    width: 4px;
    background-color: #fff;
    border-radius: 4px;

    height: 4px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #d8d8d8;
    border-radius: 4px;
  }
}
.regionSalaryBasic {
  // max-height: calc(100vh - 220px);
}
.regionBarChart,
.regionLineChart {
  display: flex;
  align-items: center;
  width: 100%;
}
.descTitle {
  color: #555;
  font-size: 16px;
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-family: ddin;
  font-weight: bold;
  font-size: 28px;
  margin-top: 22px;
}
.rmb {
  font-size: 22px;
}
.regoinBarChartContainer {
  flex: 0.7;
}
.regionLineChart {
  flex: 1;
}
.regionBarDesc {
  display: flex;
  flex: 0.3;
}
.regionBarDescItem:last-of-type {
  margin-left: 37px;
}
.search-container {
  /* margin-bottom: 24px; */
}
.pagination {
  position: relative;
  margin-top: 24px;
}

::v-deep .el-table th > .cell {
  // color: rgba(0, 0, 0, 0.85);
}
::v-deep .el-table th {
  // background-color: #ef1010;
  color: #222;
  font-weight: bold;
}
::v-deep .el-table .el-table__body-wrapper {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
::v-deep .el-table {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
::v-deep.el-table .el-table__header-wrapper .el-table__header th,
::v-deep.el-table .el-table__body-wrapper tbody .el-table__row td {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
.inputEdit {
  ::v-deep td:nth-child(2) {
    background-color: transparent;
  }
  // ::v-deep th:nth-child(2) {
  //   background-color:transparent;
  // }
  ::v-deep th {
    background-color: rgb(249, 249, 249);
  }
  ::v-deep .el-input.is-disabled .el-input__inner {
    background-color: transparent;
    border-color: transparent;
    color: #606266;
    cursor: not-allowed;
  }
}
.isDisabledEdit {
  ::v-deep th {
    background-color: rgb(249, 249, 249);
  }

  ::v-deep td:nth-child(2) {
    background-color: #ddeaff;
  }
  ::v-deep th:nth-child(2) {
    background-color: #ddeaff;
  }
  ::v-deep .el-input .el-input__inner {
    background-color: transparent;
    border-color: #ddeaff;
    color: #606266;
    cursor: not-allowed;
  }
}

::v-deep.el-form--inline .el-form-item {
  margin-right: 24px;
}
::v-deep .el-tabs__item {
  height: 40px !important;
  color: #555;
  font-size: 16px;
}
::v-deep .el-tabs__item.is-active {
  color: #1574ff;
  font-weight: bold;
}
::v-deep .el-tabs__nav-wrap::after {
  background-color: transparent;
  height: 1px;
}

::v-deep .el-button--primary {
  color: #fff;
  background-color: #1574ff;
  border-color: #1574ff;
}
.filter-item {
  margin-bottom: 12px;
}
.positionName {
  display: flex;
  width: 100vw;
  align-items: center;
  color: #333333;
  background-color: #edf6ff;
  height: 48px;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  margin-left: -56px;
  padding: 0 55px;
}
::v-deep .el-form-item {
  display: flex;
  align-items: center;
}
::v-deep .el-form-item__label {
  display: flex;
  align-items: center;
  justify-content: center;
  /* height: 27px; */
  min-width: 82px !important;
  color: #555555;
  flex-wrap: nowrap;
}
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}
::v-deep.el-popover {
  background: #3662ec;
}

::v-deep .el-button--primary.is-plain {
  color: #409eff;
  background: #fff;
  border-color: #b3d8ff;
}
.edit-button {
  margin-left: 10px;
}
.toolTipGuide {
  display: flex;
}
.toolTipItems {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.stepImageContainer {
}
.stepImage {
  width: 264px;
  height: 149px;
}
.stepDesc {
  margin-top: 14px;
  font-size: 14px;
}
.salary-scope {
  // background: #BDD8FF;
}
</style>
